package com.xujie.property_warranty_system.controller;

import com.xujie.property_warranty_system.common.Result;
import com.xujie.property_warranty_system.dto.*;
import com.xujie.property_warranty_system.entity.User;
import com.xujie.property_warranty_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class AdminController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取待审核用户列表
     */
    @GetMapping("/users/pending")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<User>> getPendingUsers() {
        try {
            List<User> users = userService.getPendingUsers();
            return Result.success(users);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取所有用户列表（保持兼容性）
     */
    @GetMapping("/users")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<PageResult<UserVO>> getUsers(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long roleId) {
        try {
            UserPageDTO pageDTO = new UserPageDTO();
            pageDTO.setPage(page);
            pageDTO.setSize(size);
            pageDTO.setKeyword(keyword);
            pageDTO.setStatus(status);
            pageDTO.setRoleId(roleId);
            
            PageResult<UserVO> result = userService.getUserPage(pageDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/users/stats")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<UserStatsDTO> getUserStats() {
        try {
            UserStatsDTO stats = userService.getUserStats();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 审核用户（保持兼容性）
     */
    @PostMapping("/users/audit")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> auditUser(@Valid @RequestBody AuditUserDTO auditDTO) {
        try {
            String message = userService.auditUser(auditDTO);
            return Result.success(message);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 审核通过用户
     */
    @PostMapping("/users/{userId}/approve")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> approveUser(@PathVariable Long userId) {
        try {
            String message = userService.approveUser(userId);
            return Result.success(message);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 拒绝用户申请
     */
    @PostMapping("/users/{userId}/reject")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> rejectUser(@PathVariable Long userId, @RequestBody Map<String, String> request) {
        try {
            String reason = request.get("reason");
            if (reason == null || reason.trim().isEmpty()) {
                return Result.error("拒绝原因不能为空");
            }
            String message = userService.rejectUser(userId, reason);
            return Result.success(message);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/users/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> updateUser(@PathVariable Long userId, @Valid @RequestBody AdminUserUpdateDTO updateDTO) {
        try {
            String message = userService.updateUserByAdmin(userId, updateDTO);
            return Result.success(message);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 重置用户密码
     */
    @PostMapping("/users/{userId}/reset-password")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> resetUserPassword(@PathVariable Long userId) {
        try {
            String message = userService.resetUserPassword(userId);
            return Result.success(message);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/users/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> deleteUser(@PathVariable Long userId) {
        try {
            String message = userService.deleteUser(userId);
            return Result.success(message);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户详细信息
     */
    @GetMapping("/users/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<UserVO> getUserDetail(@PathVariable Long userId) {
        try {
            UserVO userVO = userService.getUserDetail(userId);
            return Result.success(userVO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}